package ThematicModelProto;

import java.io.IOException;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

public class Helpers {

	static DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	static DocumentBuilder db = initDocBuilder();
	static TransformerFactory transfac = TransformerFactory.newInstance();
    static Transformer trans = initTransformer();
	
    private static Transformer initTransformer(){
	    try
	    {
	    	Transformer trans = transfac.newTransformer();
	    	return trans;
	    }catch (TransformerException e){
		      e.printStackTrace();
		}
	    return null;
	    
    }
    
    
	private static DocumentBuilder initDocBuilder(){
		try{
			DocumentBuilder db = dbf.newDocumentBuilder();
			return db;
		}catch(ParserConfigurationException pce){
			pce.printStackTrace(); 
		}
		return null;
		
	}
	
	
	public static Document parseXmlFile(String f){
		Document dom = null;
		try {
			//parse using builder to get DOM representation of the XML file
			dom = db.parse(f);
		}catch(SAXException se) {
			se.printStackTrace();
		}catch(IOException ioe) {
			ioe.printStackTrace();
		}
		return dom;
	}

	public static String xmlToString(Node node){
		if(!node.getNodeName().equals("#document")){
			trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		}else{
			trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
		}
		trans.setOutputProperty(OutputKeys.INDENT, "yes");

		// Print the DOM node

		StringWriter sw = new StringWriter();
		StreamResult result = new StreamResult(sw);
		DOMSource source = new DOMSource(node);
		try{
			trans.transform(source, result);
		}catch(TransformerException e){
			e.printStackTrace();
		}
		String xmlString = sw.toString();

		return xmlString;

	}
	
	
}
